<template>
	<view class="edit-form-container">
		<!-- 头部区域 -->
		<headerSlot :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header-content" @click="closePage()">
					<view class="header-left">
						<view class="back-btn">
							<text class="back-icon">←</text>
						</view>
					</view>
					<view class="header-center">
						<text class="page-title">发布任务</text>
					</view>
					<view class="header-right">
						<view class="placeholder"></view>
					</view>
				</view>
			</template>
		</headerSlot>

		<!-- 表单内容 -->
		<view class="form-container">
			<uni-forms :modelValue="formData" :rules="rulesForm" ref="form" validate-trigger="submit">
				<!-- 基本信息区域 -->
				<view class="form-section">
					<view class="section-header">
						<view class="section-title">
							<text class="title-text">基本信息</text>
							<view class="title-decoration"></view>
						</view>
					</view>

					<view class="form-items">
						<uni-forms-item label="任务类型" name="type">
							<uni-data-select v-model="formData.type" :clear="false"
								:localdata="rangeType"></uni-data-select>
						</uni-forms-item>

						<uni-forms-item label="联系人" name="contactName">
							<uni-easyinput type="text" v-model="formData.contactName" placeholder="请输入联系人" />
						</uni-forms-item>

						<uni-forms-item label="联系电话" name="contactPhone">
							<uni-easyinput type="text" v-model="formData.contactPhone" placeholder="请输入联系电话" />
						</uni-forms-item>

						<uni-forms-item label="任务起点" name="startAddress"
							v-if="formData.type == '搬运服务'||formData.type== '帮我取'||formData.type == '接送小孩'">
							<view class="address-input">
								<uni-easyinput :trim='true' :clearable='true' v-model="formData.startAddress"
									placeholder="填写地址信息"></uni-easyinput>
							</view>
						</uni-forms-item>

						<uni-forms-item label="任务终点" name="endAddress">
							<view class="address-input">
								<uni-easyinput :trim='true' :clearable='true' v-model="formData.endAddress"
									placeholder="填写地址信息"></uni-easyinput>
							</view>
						</uni-forms-item>

						<view class="warning-tip" v-if="formData.type == '帮我买'">
							<view class="tip-content">
								<text class="tip-icon">⚠️</text>
								<text class="tip-text">当前仅限就近购买</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 任务信息区域 -->
				<view class="form-section">
					<view class="section-header">
						<view class="section-title">
							<text class="title-text">任务信息</text>
							<view class="title-decoration"></view>
						</view>
					</view>

					<view class="form-items">
						<uni-forms-item label="取件码" name="pickupCode" v-if="formData.type== '帮我取'">
							<view class="pickup-input">
								<uni-easyinput :trim='true' :clearable='true' v-model="formData.pickupCode"
									placeholder="请输入取件码,多个用逗号分割"></uni-easyinput>
							</view>
							<view class="warning-tip">
								<view class="tip-content">
									<text class="tip-icon">🔒</text>
									<text class="tip-text">取件码接单后可见</text>
								</view>
							</view>
						</uni-forms-item>

						<template v-if="formData.type== '搬运服务'||formData.type== '帮我取'">
							<uni-forms-item label="物品类型" name="itemType">
															<uni-data-checkbox v-model="formData.itemType" :localdata="categoryType"
								@change="changeCategory" />
							</uni-forms-item>
						</template>

						<uni-forms-item label="服务时间" name="serviceTime">
							<uni-datetime-picker type="datetime" v-model="formData.serviceTime" />
						</uni-forms-item>

						<uni-forms-item label="是否仅限业主接单" name="onlyOwner" :label-width="150">
							<uni-data-checkbox v-model="formData.onlyOwner" :localdata="list" />
						</uni-forms-item>

						<uni-forms-item label="任务详情" name="description">
							<uni-easyinput :trim='true' :maxlength='-1' :clearable='true' type="textarea" autoHeight
								placeholder="请输入详情描述" v-model="formData.description"></uni-easyinput>
						</uni-forms-item>

						<uni-forms-item label="添加图片" name="picture">
							<uni-file-picker limit="6" v-model="formData.images" :image-styles="imgStyle"
								@select="uploadImages"></uni-file-picker>
						</uni-forms-item>

						<uni-forms-item label="任务赏金" name="reward">
							<view class="reward-input">
								<uni-easyinput :trim='true' :clearable='true' v-model="formData.reward"
									placeholder="请输入任务赏金"></uni-easyinput>
							</view>
							<view class="warning-tip">
								<view class="tip-content">
									<text class="tip-icon">💰</text>
									<text class="tip-text">任务佣金不能低于{{minCommission}} 元</text>
								</view>
							</view>
						</uni-forms-item>

						<uni-forms-item label="自动取消时间" name="expiresAt" :label-width="100">
							<uni-data-select v-model="formData.expiresAt" :clear="false" :localdata="autoCancelTimeTab"
								placement='top'></uni-data-select>
							<view class="warning-tip">
								<view class="tip-content">
									<text class="tip-icon">⏰</text>
									<text class="tip-text">下单n小时后无人接单;自动取消订单</text>
								</view>
							</view>
						</uni-forms-item>
					</view>
				</view>
			</uni-forms>

			<!-- 发布按钮 -->
			<view class="submit-section">
				<button class="submit-btn" @click="submitForm">
					<text class="btn-text">发布订单</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/config/config';
	import headerSlot from '@/components/header-slot.vue';
	import storage from "@/utils/storage.js";
	import FromMixin from "@/minixs/formMixin.js"
	import {
		sendServiceOrder,
		getOrderPayStatus
	} from "@/api/order.js"
	import {
		getPlatformInfo
	} from "@/api/members.js"
	import {
		WechatPay
	} from "@/utils/pay.js"

	export default {
		mixins: [FromMixin],
		components: {
			headerSlot,
		},
		data() {
			return {
				config,
				userInfo: {}, //用户信息
				categoryTypeVal: '',
				minCommission: 2,
				content: [], //时间数组
				formData: {
					type: '万能帮办', // 修改为字符串类型，与 rangeType 的值匹配
					contactName: '',
					contactPhone: '',
					startAddress: '',
					endAddress: '',
					description: '',
					reward: '',
					onlyOwner: 0,
					serviceTime: '',
					itemType: '',
					expiresAt: '',
					pickupCode: '',
					images: [],
				}, //表单对象
			}
		},
		onLoad(opt) {
			this.userInfo = storage.getUserInfo()
			this.formData.contactName = this.userInfo.nickname
			this.formData.contactPhone = this.userInfo.phone
			this.formData.startAddress = this.userInfo.community.name
			this.formData.endAddress = this.userInfo.community.name

			getPlatformInfo("min_order_amount").then(res => {
				this.minCommission = res.data.data.value
				// 更新验证规则中的最低金额
				this.updateRewardValidation()
			})
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rulesForm)
			// 如果 minCommission 已经获取到，更新验证规则
			if (this.minCommission && this.minCommission !== 2) {
				this.updateRewardValidation()
			}
		},
		methods: {
			//提交表单
			submitForm() {
				this.$refs.form.validate().then(() => {
					uni.showLoading({
						mask: true,
						title: '发布中...'
					})
					this.$set(this.formData, 'onlyOwner', this.formData.onlyOwner === 1)
					this.$set(this.formData, 'openid', this.userInfo.openid)
					if (this.formData.pickupCode) {
						this.$set(this.formData, 'pickupCode', this.formData.pickupCode.split(','))
					}
					sendServiceOrder(this.formData).then(res => {
						uni.hideLoading()
						if (res.data.code == 200) {
							let layData = res.data.data
							// 订单创建成功，调用微信支付
							this.handlePayment(layData)
						} else {
							uni.showToast({
								title: res.data.message || "订单发送失败",
								icon: "error",
							});
						}
					}).catch((err) => {
						uni.hideLoading()
						console.log(err);
						uni.showToast({
							title: err.data?.message || "订单发送失败",
							icon: "error",
						});
					})
				}).catch((err) => {
					console.log('表单验证失败:', err);
					// 显示验证错误提示
					if (err && err.length > 0) {
						uni.showToast({
							title: err[0].errorMessage || '请检查表单填写',
							icon: 'none',
							duration: 2000
						});
					}
				})
			},
			handlePayment(layData) {
				uni.showLoading({
					mask: true,
					title: '支付中...'
				})
				// 发起微信支付
				wx.requestPayment({
					...layData.wxPayParams,
					success: () => {
						uni.showLoading({
							mask: true,
							title: "查询支付状态中...",
						})
						getOrderPayStatus({
							orderId: layData.orderId
						}).then(res => {
							uni.hideLoading();
							uni.redirectTo({
								url: '/pages/mePages/myService'
							})
						}).catch(err => {
							uni.hideLoading();
							console.log('查询支付状态失败:', err);
							uni.showToast({
								title: "支付状态查询失败",
								icon: "error"
							});
						})
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: "支付失败",
							icon: "error"
						});
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/mePages/myService'
							}, 1000)
						})
					}
				});
			},
			changeCategory(e) {
				// itemType 现在直接绑定到 formData.itemType，不需要手动设置
				// 这个方法可以保留用于其他逻辑处理
			},
			openDodge() {
				this.$refs.model.open();
			},
			closePage() {
				uni.navigateBack()
			},
			// 更新赏金验证规则
			updateRewardValidation() {
				if (this.$refs.form) {
					// 更新 reward 字段的验证规则
					this.rulesForm.reward.rules[1].validateFunction = (rule, value, data, callback) => {
						const numValue = Number(value)
						// 校验逻辑
						if (isNaN(numValue)) {
							callback('必须为数字')
						} else if (numValue < this.minCommission) {
							callback(`任务赏金不能低于${this.minCommission}元`)
						}
						return true
					}
					// 重新设置验证规则
					this.$refs.form.setRules(this.rulesForm)
				}
			},
		},
	}
</script>

<style scoped lang="scss">
	.edit-form-container {
		background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
		min-height: 100vh;
	}

	// 头部样式
	.header-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		width: 100%;

		.header-left {
			.back-btn {
				width: 64rpx;
				height: 64rpx;
				background: rgba(255, 255, 255, 0.9);
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
				transition: all 0.3s ease;

				&:active {
					transform: scale(0.95);
					background: rgba(255, 255, 255, 1);
				}

				.back-icon {
					font-size: 32rpx;
					color: #333;
					font-weight: 600;
				}
			}
		}

		.header-center {
			flex: 1;
			text-align: center;

			.page-title {
				font-size: 36rpx;
				font-weight: 700;
				color: #333;
			}
		}

		.header-right {
			.placeholder {
				width: 64rpx;
			}
		}
	}

	// 表单容器
	.form-container {
		padding: 24rpx;
	}

	// 表单区域
	.form-section {
		background: white;
		border-radius: 24rpx;
		margin-bottom: 24rpx;
		overflow: hidden;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
		position: relative;
		z-index: 1;

		.section-header {
			padding: 32rpx 32rpx 24rpx;
			border-bottom: 1rpx solid #f0f0f0;

			.section-title {
				display: flex;
				align-items: center;

				.title-text {
					font-size: 32rpx;
					font-weight: 700;
					color: #333;
					margin-right: 16rpx;
				}

				.title-decoration {
					width: 6rpx;
					height: 28rpx;
					background: linear-gradient(135deg, #FF6B35 0%, #FE6100 100%);
					border-radius: 3rpx;
				}
			}
		}

		.form-items {
			padding: 32rpx;
			position: relative;
			z-index: 2;
		}
	}

	// 地址输入框
	.address-input {
		width: 100%;
	}

	// 取件码输入框
	.pickup-input {
		width: 100%;
	}

	// 赏金输入框
	.reward-input {
		width: 100%;
	}

	// 警告提示
	.warning-tip {
		margin-top: 16rpx;

		.tip-content {
			display: flex;
			align-items: center;
			background: #FFF7E6;
			border: 1rpx solid #FFE7BA;
			border-radius: 12rpx;
			padding: 16rpx 20rpx;

			.tip-icon {
				font-size: 24rpx;
				margin-right: 12rpx;
			}

			.tip-text {
				font-size: 26rpx;
				color: #FF6B35;
				font-weight: 500;
			}
		}
	}

	// 提交区域
	.submit-section {
		padding: 32rpx 0;

		.submit-btn {
			width: 100%;
			height: 88rpx;
			background: linear-gradient(135deg, #FF6B35 0%, #FE6100 100%);
			border-radius: 44rpx;
			border: none;
			box-shadow: 0 8rpx 24rpx rgba(254, 97, 0, 0.3);
			transition: all 0.3s ease;
			display: flex;
			align-items: center;
			justify-content: center;

			&:active {
				transform: translateY(-2rpx);
				box-shadow: 0 12rpx 32rpx rgba(254, 97, 0, 0.4);
			}

			.btn-text {
				color: white;
				font-size: 32rpx;
				font-weight: 700;
			}
		}
	}

	// 兼容旧样式
	.header_slot {
		padding: 0 32rpx;
		width: 100%;
		font-weight: 500;
		font-size: 36rpx;
		color: #2C2622;
	}

	::v-deep .uni-section-header {
		padding: 24rpx 0 !important;
	}

	::v-deep .uni-data-select {
		z-index: 999 !important;
	}

	::v-deep .uni-data-select__input-box {
		z-index: 999 !important;
	}

	::v-deep .uni-data-select__selector {
		z-index: 1000 !important;
	}

	::v-deep .uni-data-select__selector-item {
		z-index: 1000 !important;
	}

	::v-deep .uni-datetime-picker {
		z-index: 999 !important;
	}

	::v-deep .uni-datetime-picker__container {
		z-index: 1000 !important;
	}

	.form_box {
		min-height: 200px;
		margin: 24rpx;
		padding: 24rpx;
		background-color: #fff;
	}

	.warn_tip {
		font-size: 24rpx;
	}

	.take_weight {
		margin: 0 8rpx;
		width: 36rpx;
		height: 36rpx;
		line-height: 34rpx;
		text-align: center;
		border-radius: 50%;
		border: 2px solid #e0e5ed;
		background-color: #fff;
		font-weight: 700;
	}

	.release_btn {
		margin-top: 32rpx;
	}
</style>